package com.dodo.blog.ui.component.input;

import com.dodo.blog.ui.component.container.Container;
import com.dodo.blog.ui.util.Localization;

import java.util.Arrays;
import java.util.List;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class Select<T>
        extends Container
{
    private static final long serialVersionUID = 1L;

    public Select( String id, T[] choices, IChoiceRenderer renderer )
    {
        this( id, Arrays.asList( choices ), renderer, false );
    }

    public Select( String id, List<T> choices, IChoiceRenderer renderer )
    {
        this( id, choices, renderer, false );
    }

    public Select( String id, T[] choices, IChoiceRenderer renderer, boolean allowEmptyItem )
    {
        this( id, Arrays.asList( choices ), renderer, allowEmptyItem );
    }

    public Select( String id, List<T> choices, IChoiceRenderer renderer, boolean allowEmptyItem )
    {
        super( Tag.SELECT );
        setId( id );
        setName( id );

        if ( allowEmptyItem )
        {
            add( new Option( getEmptyItemString() ) );
        }

        for ( Object object : choices )
        {
            add( new Option( renderer.getValue( object ), renderer.getLabel( object ) ) );
        }
    }

    public Select setAutoFocus( boolean autoFocus )
    {
        if ( autoFocus )
        {
            setAttribute( Attribute.AUTOFOCUS );
        }
        else
        {
            removeAttribute( Attribute.AUTOFOCUS );
        }

        return this;
    }

    public String getEmptyItemString()
    {
        return Localization.localize( "select" );
    }
}
